package org.nox.helloseries.server.services.html.impl;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.nox.helloseries.domain.Tracker;
import org.nox.helloseries.factory.HelloSeriesServiceFactory;
import org.nox.helloseries.server.connector.html.XPathSearcher;
import org.nox.helloseries.server.services.html.HTMLSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultHTMLSearchService implements HTMLSearchService
{
    private static final Logger LOG = LoggerFactory.getLogger( DefaultHTMLSearchService.class );

    private static final String DOWNLOAD_LINK_FTB_XPATH = "//a[@class='dl_link']";

    private static final String DOWNLOAD_LINK_T411_XPATH = "//a[text()='T&#233;l&#233;charger']";

    private XPathSearcher xPathSearcher = HelloSeriesServiceFactory.createOrGetService( XPathSearcher.class );

    @Override
    public String searchForDownloadLink( String url, Tracker tracker, HttpEntity httpEntity )
    {
        String newHost = null;
        switch ( tracker.getNomTracker() )
        {
        case FRENCHTORRENTDB:
            LOG.info( "XPath de recherche pour le lien de téléchargement : " + DOWNLOAD_LINK_FTB_XPATH );
            newHost = xPathSearcher.getAttributeFromXpath( httpEntity, DOWNLOAD_LINK_FTB_XPATH, "href" );
            if ( newHost != null )
            {
                newHost = url.replaceAll( "/\\?section.*", newHost );
                LOG.info( "Lien de téléchargement trouvé : " + newHost );
            }
            else
            {
                LOG.debug( "Aucune URL de téléchargement trouvé via XPath" );
            }
            break;
        case TORRENT411:
            LOG.info( "XPath de recherche pour le lien de téléchargement : " + DOWNLOAD_LINK_T411_XPATH );
            newHost = xPathSearcher.getAttributeFromXpath( httpEntity, DOWNLOAD_LINK_T411_XPATH, "href" );
            if ( newHost != null )
            {
                if ( newHost.contains( "login" ) )
                {
                    newHost = url.replaceAll( "/torrents.*", "/torrents/download/?id=" + StringUtils.substringAfter( newHost, "/t/" ) );
                }
                else
                {
                    newHost = url.replaceAll( "/torrents.*", newHost );
                }
                LOG.info( "Lien de téléchargement trouvé : " + newHost );
            }
            else
            {
                LOG.debug( "Aucune URL de téléchargement trouvé via XPath" );
            }
        default:
            break;
        }
        return newHost;
    }
}
